CREATE OR REPLACE FUNCTION "public"."p_test_insert_trigger"()
  RETURNS "pg_catalog"."trigger" AS $BODY$
DECLARE
    curDD 		varchar(8);		-- 'YYYYMMDD'字串,用做分区子表的后缀
    isExist 		INTEGER;		-- 分区子表,是否已存在
		strSQL  		text;
		startTime 		text;
    endTime		text;
		TG_RELNAME   varchar(20);
		time_column_name varchar(20);
BEGIN
	TG_RELNAME :='p_test';
	time_column_name :='collect_time';

	-- 判断对应分区表 是否已经存在?
	EXECUTE 'SELECT $1.'||time_column_name INTO strSQL USING NEW;
	curDD := to_char(strSQL::timestamp , 'YYYYMMDD');
	select count(*) INTO isExist from pg_class where relname = (TG_RELNAME||'_'||curDD);
	IF (isExist = 0) THEN
	  -- 创建子分区表
		startTime :=curDD||' 00:00:00.000';
	  endTime := to_char( startTime::timestamp + interval '1 DAY', 'YYYY-MM-DD HH24:MI:SS.MS');
		strSQL := 'CREATE TABLE IF NOT EXISTS '||TG_RELNAME||'_'||curDD||
                  ' ( CHECK('||time_column_name||'>='''|| startTime ||''' AND '
                             ||time_column_name||'< '''|| endTime ||''' )
                          ) INHERITS ('||TG_RELNAME||') ;'  ;  
    EXECUTE strSQL;
		
		-- 创建索引
		strSQL := 'CREATE INDEX '||TG_RELNAME||'_'||curDD||'_INDEX_'||time_column_name||' ON '
							||TG_RELNAME||'_'||curDD||' ('||time_column_name||');' ;
		EXECUTE strSQL;
	END IF;
	-- 插入数据到子分区!
	strSQL := 'INSERT INTO '||TG_RELNAME||'_'||curDD||' SELECT $1.*';
	EXECUTE strSQL USING NEW;
	RETURN NULL; 
END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100